package com.cskaoyan.service.admin.impl;

import com.cskaoyan.bean.BasePageInfo;
import com.cskaoyan.bean.MarketUser;
import com.cskaoyan.bean.MarketUserExample;
import com.cskaoyan.bean.param.CommonData;
import com.cskaoyan.mapper.MarketUserMapper;
import com.cskaoyan.service.admin.UserService;
import com.cskaoyan.util.MD5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author stone
 * @date 2022/06/25 11:11
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    MarketUserMapper userMapper;

    /**
     * username模糊查找时先trim一下
     *
     * @param username
     * @param mobile
     * @param id
     * @param info
     * @return userList
     * @auther LC
     */
    @Override
    public CommonData<MarketUser> query(String username, String mobile, Integer id, BasePageInfo info) {
        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria criteria = marketUserExample.createCriteria();
        if (!StringUtils.isEmpty(username)) {
            username = "%" + username.trim() + "%";
            criteria.andUsernameLike(username);
        }
        if (!StringUtils.isEmpty(mobile)) {
            mobile = "%" + mobile.trim() + "%";
            criteria.andMobileLike(mobile);
        }
        criteria.andDeletedEqualTo(false);
        List<MarketUser> marketUsers = userMapper.selectByExample(marketUserExample);
        // List<MarketUser> users = userMapper.select(username, mobile, id, info.getSort(), info.getOrder());
        PageInfo<MarketUser> pageInfo = new PageInfo(marketUsers);
        return CommonData.data(pageInfo);
    }

    @Override
    public MarketUser queryById(Integer id) {
        MarketUser user = userMapper.selectByPrimaryKey(id);
        // MarketUser user = userMapper.selectById(id);
        return user;
    }

    @Transactional
    @Override
    public int update(MarketUser user) {
        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria criteria = marketUserExample.createCriteria();
        criteria.andIdEqualTo(user.getId());
        user.setUpdateTime(new Date());
        MarketUser marketUser = userMapper.selectByPrimaryKey(user.getId());
        if(!user.getPassword().equals(marketUser.getPassword())){
            user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        }
        user.setId(null);
        int affectRows = userMapper.updateByExampleSelective(user, marketUserExample);
        // int affectRows = userMapper.update(user);
        return affectRows;
    }
}
